/**
 * created by 小卷毛, 2021-5-6
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl

import android.content.Intent
import android.os.Build
import android.webkit.WebView
import androidx.multidex.MultiDexApplication
import com.amap.api.location.AMapLocationClient
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.OkGoHelper
import com.lzy.okgo.utils.OkLogger
import com.rzico.sbl.ui.GuideActivity
import com.rzico.sbl.ui.LoginActivity
import com.rzico.sbl.ui.MessageActivity
import com.tencent.qcloud.tuicore.TUILogin
import com.tim.library.*
import com.tim.library.utils.SettingsUtil
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.xinnuo.badge.BadgeUpdateManager.updateBadgeNumber
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.listener.registerActivityLifecycle
import com.xinnuo.common_ui.oss.OSSHelper
import com.xinnuo.common_ui.viewmodel.BaseViewModel
import com.xinnuo.objectbox.getBoxEuery
import com.xinnuo.objectbox.model.AppLoginData
import com.xinnuo.objectbox.model.AppLoginData_
import io.reactivex.plugins.RxJavaPlugins
import me.jessyan.autosize.AutoSizeConfig
import net.mikaelzero.mojito.Mojito
import net.mikaelzero.mojito.loader.glide.GlideImageLoader
import net.mikaelzero.mojito.view.sketch.SketchImageLoadFactory

/**
 * 描 述：
 * 作 者：小卷毛  2021-05-06 13:30
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
@Suppress("unused")
class Application : MultiDexApplication() {

    // 是否在后台时被踢下线
    private var mBackgroundTickedQ = false

    override fun onCreate() {
        super.onCreate()

        // WebView进程崩溃
        initPieWebView()

        // 屏幕适配
        AutoSizeConfig
            .getInstance()
            .isCustomFragment = true

        // OkGo初始化
        OkGoHelper.initOkGo(
            app = this@Application,
            logTag = "Spirit_Water",
            isEnable = BuildConfig.DEBUG
        )

        // RxJava 取消订阅后抛出异常处理
        RxJavaPlugins.setErrorHandler { it.printStackTrace() }

        // OSS存储初始化
        OSSHelper.manager.initOSS(this@Application)

        // LiveDataBus初始化
        LiveEventBus.config()
            .lifecycleObserverAlwaysActive(true)
            .enableLogger(BuildConfig.DEBUG)

        // 获取当前版本号
        BaseViewModel.mVersion = getVersion()

        // AMap调用SDK任何接口前先调用更新隐私合规updatePrivacyShow、updatePrivacyAgree两个接口并且参数值都为true，
        // 若未正确设置有崩溃风险
        AMapLocationClient.updatePrivacyShow(this, true, true)
        AMapLocationClient.updatePrivacyAgree(this, true)

        // 腾讯云初始化
        initTuiKit()

        // Mojito初始化
        Mojito.initialize(
            GlideImageLoader.with(this),
            SketchImageLoadFactory()
        )

        // 友盟统计
        UMConfigure.setLogEnabled(true)
        UMConfigure.init(this, "652d024d58a9eb5b0aeeca72", getOSName(), UMConfigure.DEVICE_TYPE_PHONE, null)
        UMConfigure.setProcessEvent(true)
        MobclickAgent.setCatchUncaughtExceptions(false)
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)

        // 应用生命周期回调
        registerActivityLifecycle {
            // 应用切换到前台
            onForeground {
                (!isLogin && mBackgroundTickedQ)
                    .condition {
                        mBackgroundTickedQ = false
                        startActivityEx<LoginActivity>(
                            "offLine" to true
                        ) { newTask() }
                    }

                // 腾讯云设置在线模式
                (isLogin && TUILogin.isUserLogined())
                    .condition {
                        doForeground {
                            onSuccess { OkLogger.i("在线推送成功") }
                            onError { _, desc ->
                                OkLogger.e("在线推送失败：$desc")
                            }
                        }
                    }
            }

            // 应用切换到后台
            onBackground {
                // 清除角标
                updateBadgeNumber()
            }
        }
    }

    /**
     * 高版本 WebView 多进程崩溃问题
     */
    private fun initPieWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val processName = getProcessName()
            if (processName != packageName) {
                WebView.setDataDirectorySuffix(processName)
            }
        }
    }

    /**
     * 腾讯云初始化
     */
    private fun initTuiKit() {
        // 获取设备信息
        initBuildInfo()

        // 设置离线消息点击事件
        registerNotifyEvent {
            startActivityEx<GuideActivity> { newTask() }
        }

        // 设置登录状态的监听
        addTUILoginListener {
            onKickedOffline {
                longToast("当前${getString(R.string.app_name)}账户在其他设备上登录")

                // AndroidQ 禁止从后台启动Activity
                when {
                    isRunningForeground() ||
                            Build.VERSION.SDK_INT < Build.VERSION_CODES.Q ->
                        startActivityEx<LoginActivity>("offLine" to true) { newTask() }

                    else -> {
                        mBackgroundTickedQ = true
                        isLogin = false
                    }
                }
            }
        }

        // 设置高级消息的全局监听
        addAdvancedMsgListener {
            onRecvNewMessage { message ->
                // 设置消息已读
                if (!message.isRead) {
                    cleanC2CMessageUnRead(message.sender) {
                        onSuccess { OkLogger.i("消息已读成功") }
                        onError { _, desc ->
                            OkLogger.e("消息已读失败：$desc")
                        }
                    }
                }

                // 发送自定义通知
                MessageNotification
                    .getInstance(this@Application)
                    .notify(
                        message,
                        R.mipmap.ic_launcher,
                        Intent(
                            this@Application,
                            MessageActivity::class.java
                        ).newTask()
                    )

                val notifyEnable =
                    getBoxEuery<AppLoginData>()
                        .equal(AppLoginData_.isLogin, true)
                        .build()
                        .findFirst()
                        ?.notifyEnable ?: "1"

                // 播报自定义语音
                if (notifyEnable == "1") {
                    SettingsUtil
                        .getAndroidConfig(message.offlinePushInfo)
                        ?.let { info ->
                            SettingsUtil
                                .getAndroidUri(info)
                                ?.let {
                                    SoundHelper
                                        .getInstance()
                                        .playSound(
                                            when {
                                                "/raw/h0" in it -> R.raw.h0
                                                "/raw/h10" in it -> R.raw.h10
                                                "/raw/h11" in it -> R.raw.h11
                                                "/raw/h1" in it -> R.raw.h1
                                                "/raw/h2" in it -> R.raw.h2
                                                "/raw/h3" in it -> R.raw.h3
                                                "/raw/h4" in it -> R.raw.h4
                                                "/raw/h5" in it -> R.raw.h5
                                                "/raw/h6" in it -> R.raw.h6
                                                "/raw/h7" in it -> R.raw.h7
                                                "/raw/h8" in it -> R.raw.h8
                                                "/raw/h9" in it -> R.raw.h9

                                                else -> R.raw.h0
                                            }
                                        )
                                }
                        }
                }
            }
        }
    }

}